<?php
/**
 * (exporter)
 */
namespace App\Exporter\SalesReport;

use App\Models\Product\ProductClassify;
use App\Models\SalesReport\DailyCv;
use App\Models\SalesReport\DailySv;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
class DailyCVAExporter extends ExcelExporter implements WithMapping,WithHeadings
{

    protected $fileName = '品类日销量和库存-站点.csv';

    public function headings(): array
    {
        $head1 = ['季节性','品类','站点'];
        $head2 = [];
        for($i = DailyCv::V_NUM; $i >= 1; $i--){
            $head2[] = date('y/m/d',strtotime("-$i days"));
        }
        $head3 = ['3天AVG','7天AVG','15天AVG','30天AVG','AVG','销量趋势','FBA在库','FBA在途','国内在库','国内在途','海外仓在库','海外仓在途','FBA&ALL库存系数'];
        return array_merge($head1,$head2,$head3);
    }

    public function map($model) : array
    {
        $season = ProductClassify::$_season[$model->classify->season ?? 3];
        $title = $model->classify->title ?? '';
        $data1 = [$season,$title,''];
        $data2 = [];
        for($i = DailyCv::V_NUM; $i >= 1; $i--){
            $data2[] = $model->{"day$i"} ?: 0;
        }
        $data3 = [
            $model->avg3 ?: 0,
            $model->avg7 ?: 0,
            $model->avg15 ?: 0,
            $model->avg30 ?: 0,
            $model->avg ?: 0,
            array_key_exists($model->sales_status,DailySv::$_salesStatus) ? DailySv::$_salesStatus[$model->sales_status] : '',
            $model->fba_instant_num ?: 0,
            $model->fba_transit_num ?: 0,
            $model->cn_instant_num ?: 0,
            $model->cn_transit_num ?: 0,
            $model->os_instant_num ?: 0,
            $model->os_transit_num ?: 0,
            DailySv::getInvFactor($model)
        ];
        $count = 0;
        $data = [];
        $data[$count] = array_merge($data1,$data2,$data3);
        foreach($model->cva as $item){
            $count++;
            $_data1 = [$season,$title,$item->area->area ?? ''];
            $_data2 = [];
            for($i = DailyCv::V_NUM; $i >= 1; $i--){
                $_data2[] = $item->{"day$i"} ?: 0;
            }
            $_data3 = [
                $item->avg3 ?: 0,
                $item->avg7 ?: 0,
                $item->avg15 ?: 0,
                $item->avg30 ?: 0,
                $item->avg ?: 0,
                array_key_exists($item->sales_status,DailySv::$_salesStatus) ? DailySv::$_salesStatus[$item->sales_status] : '',
                $item->fba_instant_num ?: 0,
                $item->fba_transit_num ?: 0,
                $item->cn_instant_num ?: 0,
                $item->cn_transit_num ?: 0,
                $item->os_instant_num ?: 0,
                $item->os_transit_num ?: 0,
                DailySv::getInvFactor($item)
            ];
            $data[$count] = array_merge($_data1,$_data2,$_data3);
        }
        return $data;
    }
}
